import React, { Component } from "react";
import { connect } from "react-redux";
import { loginUser } from "../../actions/authActions.js";
import PropTypes from "prop-types";
import { Message } from "element-ui";
import { withRouter } from "react-router-dom";
import TextFiledGroup from "../../common/TextFiledGroup.jsx";

class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: "",
      password: "",
      errors: {}
    };
  }
  onChange = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };
  onSubmit = e => {
    e.preventDefault();
    const newUser = {
      email: this.state.email,
      password: this.state.password
    };
    // console.log(newUser);
    this.props.loginUser(newUser);
  };

  componentDidMount() {
    if (this.props.auth.isAuthenticated) {
      this.props.history.push("/dashboard");
    } else {
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.auth.isAuthenticated) {
      Message({
        message: "登录成功",
        type: "success",
        duration: 1500
      });
      setTimeout(() => {
        this.props.history.push("/dashboard");
      }, 1500);
    }
  }
  render() {
    // const { errors } = this.state;
    return (
      <div className="login">
        <div className="container">
          <div className="row">
            <div className="col-md-8 m-auto">
              <h1 className="display-4 text-center">登录</h1>
              <p className="lead text-center">用正确的账号登录</p>
              <form onSubmit={this.onSubmit}>
                <TextFiledGroup
                  type="email"
                  onChange={this.onChange}
                  placeholder="邮箱地址"
                  name="email"
                  value={this.state.email}
                ></TextFiledGroup>
                <TextFiledGroup
                  type="password"
                  onChange={this.onChange}
                  placeholder="密码"
                  name="password"
                  value={this.state.password}
                ></TextFiledGroup>
                <input type="submit" className="btn btn-info btn-block mt-4" />
              </form>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
Login.propTypes = {
  loginUser: PropTypes.func.isRequired,
  auth: PropTypes.object.isRequired,
  errors: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  auth: state.auth,
  errors: state.errors
});

export default connect(mapStateToProps, { loginUser })(withRouter(Login));
